<?php
namespace Managers;
use Engine\Functions as FUNCTS;
use Engine\Constants\GLConstants as CONSTS;
use Engine\Auth\CurrentUser as USER;
use Engine\Auth;


class AutoLog extends \Lib\Model\DoctrineManager{

    public function createLogEntity($typeLog, $objectId, $user = false, $createdAt = null){
        
        if(!$user || !$user->getUserId()){
            $user = NULL;
        }
        
        $em = $this->getEntityManager();
        $em->getConnection()->beginTransaction();
        try{
            
            $log = new \Entities\AutoLog();
            $log->setTypeLog($typeLog);
            $log->setObjectId($objectId);
            
            if(!$createdAt){
                $createdAt = new \DateTime();
            }

            $log->setCreatedAt($createdAt);
                if (isset($user) && $user->getUserId()){
                    $log->setUser($em->getReference('Entities\Profile', $user->getUserId()));
                }else{
                    $log->setUser(NULL);
                }
            $em->persist($log);
            $em->flush();
            $em->getConnection()->commit();
            
        } catch (Exception $exc) {
            print $exc;
            $em->getConnection()->rollback();
        }
        
        
    }
 
    public function recreateHistory(){
        
        $mManager = new \Managers\Message();
        
        $allMessagesCreates = $mManager->getAllMessages();
        
        foreach($allMessagesCreates as $event){
            
            
            if ($event->getParentId() == $event->getMessageId()){
                $logType =  CONSTS::$LOG_CONST['ADD_PUB'];
                $this->createLogEntity($logType, $event->getMessageId(), $event->getUser()?:new \Entities\Profile(), $event->getCreatedAt());
                
                $comments = $mManager->getAllComments($event->getMessageId());

                foreach($comments as $oneComment){
                    
                    $this->createLogEntity(CONSTS::$LOG_CONST['COM_PUB'], $oneComment->getParentId(), $oneComment->getUser()?:new \Entities\Profile(), $oneComment->getCreatedAt());
                }
            }else{
                $logType = CONSTS::$LOG_CONST['UPD_PUB'];
                $this->createLogEntity($logType, $event->getParentId(), $event->getUser()?:new \Entities\Profile(), $event->getCreatedAt());
            }
            
        }
        

                
       
        
        
    }
    
}